package org.aiforum.frountend.service;

import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;

import org.aiforum.domain.User;
import org.aiforum.frountend.common.CacheContext;
import org.aiforum.frountend.common.Response;
import org.aiforum.frountend.dao.UserDao;
import org.aiforum.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户业务实现类
 * @author VIC
 *
 */
@Service("userService")
@Transactional(value=TxType.REQUIRED)
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserDao userDao;

	public Response register(User user) {
		
		// 检查注册的账号是否存在
		Response response = checkAccount(user);
		if(response.isState()){
			// 账号被占用
			response.setState(false);
			return response;
		}
		
		// 密码加密
		user.setPassword(MD5Util.encryptMD5(user.getPassword()));
		
		// 保存用户
		user.setState(1);
		userDao.persist(user);
		response.setState(true);
		response.setMessage("register success");
		
		// 记录注册日志
		
		// 发送注册消息
		
		// 返回
		
		return response;
	}

	public Response checkAccount(User user) {
		
		Response response = new Response();
		boolean state = null != userDao.quaryByAccount(user.getAccount());
		if(state){
			response.setState(state);
			response.setMessage("accoutn exists");
		}
		return response;
	}

	@Override
	public Response login(User user) {
		
		Response response =new Response();
		
		// 检查验证码是否正确
		
		// 检查账号是否存在
		User oldUser = searchByAccount(user.getAccount());
		if(null == oldUser){
			response.setMessage("account not exists");
			return response;
		}
		
		// 检查账号是否可用
		
		// 如果匹配密码成功，表示登录成功
		if(oldUser.getPassword().equals(MD5Util.encryptMD5(user.getPassword()))){
			response.setState(true);
			response.setMessage("login success");
			
			// 记录登录认证信息
			long cacheTime = System.currentTimeMillis() + 720000;// 缓存12分钟
			// 使用用户内容构建登录Token(令牌)
			// 1. 该Token在此作为缓存KEY使用
			// 2. 该Token在用户登录认证拦截器中作为获取用户登录凭证使用
			// 3. 该Token在用户退出时删除用户登录信息时使用
			String token = MD5Util.encryptMD5(user.toString());
			// 将Token输出到Action中使用
			response.setData(token);
			CacheContext.setCache(token, oldUser, cacheTime);
			
			// 记录登录日志
			
			// 发送邮件短信
		}else{
			response.setMessage("password error");
		}
		
		return response;
	}

	@Override
	public User searchByAccount(String account) {
		return userDao.quaryByAccount(account);
	}

	@Override
	public void logout(String token) {
		CacheContext.delCache(token);
	}

}
